package com.ruoyi.system.service.vantservice.orderservice.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.github.wxpay.sdk.WXPayConfig;
import com.ruoyi.common.config.AliDevPayConfig;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.ResultMap;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.DistributionSub;
import com.ruoyi.system.domain.MoneyPercentage;
import com.ruoyi.system.domain.customer.CustomerLogin;
import com.ruoyi.system.domain.distribution.CashManagement;
import com.ruoyi.system.domain.distribution.DistributionSubstations;
import com.ruoyi.system.domain.distribution.PlatformTerrace;
import com.ruoyi.system.domain.supe.Commission;
import com.ruoyi.system.domain.zhuangxiumain.orderformMain.OrderMaster;
import com.ruoyi.system.domain.zhuangxiumain.shopMain.SupplierInfo;
import com.ruoyi.system.domain.zhuangxiumain.vo.AfterSaleVo;
import com.ruoyi.system.domain.zhuangxiumain.vo.OrderVo;
import com.ruoyi.system.domain.zhuangxiumain.vo.RentalVo;
import com.ruoyi.system.domain.zhuangxiumain.vo.ZhiFuVo;
import com.ruoyi.system.mapper.DistributionSubMapper;
import com.ruoyi.system.mapper.MoneyPercentageMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.customer.CustomerLoginMapper;
import com.ruoyi.system.mapper.distribution.CashManagementMapper;
import com.ruoyi.system.mapper.distribution.DistributionSubstationsMapper;
import com.ruoyi.system.mapper.distribution.PlatformTerraceMapper;
import com.ruoyi.system.mapper.vant.order.ApiOrderMasterMapper;
import com.ruoyi.system.mapper.zhuangxiumapper.CommissionMapper;
import com.ruoyi.system.mapper.zhuangxiumapper.shopMapper.SupplierInfoMapper;
import com.ruoyi.system.service.customer.CommissionService;
import com.ruoyi.system.service.vantservice.orderservice.ApiOrderMasterService;
import com.ruoyi.system.utils.TokenUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 惠普 on 2020/12/24 9:55
 */
@Service("apiOrderMasterService")
public class ApiOrderMasterServiceImpl implements ApiOrderMasterService{
    @Resource
    private ApiOrderMasterMapper apiOrderMasterMapper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public String order(OrderMaster orderMaster) {
        //这里你可以做一些存表操作..具体根据你们自己的业务来操作...
        String orderString = "";//这个字符串是用来返回给前端的
        String orderNo = "12345678";//这行代码是生成一个商户的订单号..根据你们自己的业务需求去生成就可以了..
        System.err.println("==================支付宝下单,商户订单号为：" + orderNo);


        try {
            AliDevPayConfig aliDevPayConfig= new  AliDevPayConfig(); //实例化上面的那个配置类..
            //实例化客户端（参数：网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型），为了取得预付订单信息
            AlipayClient alipayClient = new DefaultAlipayClient(AliDevPayConfig.URL, aliDevPayConfig.APPID,
                    AliDevPayConfig.RSA_PRIVATE_KEY, AliDevPayConfig.FORMAT, AliDevPayConfig.CHARSET,
                    AliDevPayConfig.ALIPAY_PUBLIC_KEY, AliDevPayConfig.SIGNTYPE);
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeAppPayRequest ali_request = new AlipayTradeAppPayRequest();
            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            //业务参数传入,可以传很多，参考API
            //model.setPassbackParams(URLEncoder.encode(request.getBody().toString())); //公用参数（附加数据）
            //对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
            model.setBody("具体描述信息.例如QQ币充值");
            //商品名称
            model.setSubject("例:QQ币");
            //商户订单号(根据业务需求自己生成)
            model.setOutTradeNo(orderNo);
            //交易超时时间 这里的30m就是30分钟
            model.setTimeoutExpress("30m");
            //支付金额 后面保留2位小数点..不能超过2位

            model.setTotalAmount("10.00");
            //销售产品码（固定值） //这个不做多解释..看文档api接口参数解释
            model.setProductCode("QUICK_MSECURITY_PAY");
            ali_request.setBizModel(model);
            //异步回调地址（后台）//这里我在上面的aliPayConfig有讲..自己去看
            ali_request.setNotifyUrl(AliDevPayConfig.notify_url);
            System.err.println("====================异步通知的地址为：" + ali_request.getNotifyUrl());
            //同步回调地址（APP）同上
            ali_request.setReturnUrl(AliDevPayConfig.return_url);
            System.err.println("====================同步通知的地址为：" + ali_request.getReturnUrl());

            // 这里和普通的接口调用不同，使用的是sdkExecute
            //返回支付宝订单信息(预处理)
            AlipayTradeAppPayResponse alipayTradeAppPayResponse = alipayClient.sdkExecute(ali_request);
            //就是orderString 可以直接给APP请求，无需再做处理。
            orderString = alipayTradeAppPayResponse.getBody();
            System.out.println(orderString);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.err.println("与支付宝交互出错，未能生成订单，请检查代码！");
        }
        return orderString;

    }

    /**
     * 订单售后查询
     * @param afterSaleVo
     * @return
     */
    @Override
    public List<AfterSaleVo> selectAfterSaleVoList(AfterSaleVo afterSaleVo) {
        return apiOrderMasterMapper.selectAfterSaleVoList(afterSaleVo);
    }

    /**
     * 订单列表信息
     * @param orderVo
     * @return
     */
    @Override
    public List<OrderVo> selectOrderVoList(OrderVo orderVo) {
        List<OrderVo> orderVos = apiOrderMasterMapper.selectOrderVoList(orderVo);
        for (int i = 0; i < orderVos.size(); i++) {
            if (orderVos.get(i).getPicUrl() == null && !"".equals(orderVos.get(i).getPicUrl())){
                if (!"".equals(orderVos.get(i).getSupplierId()) || orderVos.get(i).getProductName() != null && !"".equals(orderVos.get(i).getProductName())){
                    RentalVo rentalVo = new RentalVo();
                    rentalVo.setSupplierId(orderVos.get(i).getSupplierId()+"");
                    rentalVo.setRentalName(orderVos.get(i).getProductName());
                    List<RentalVo> rentalVos = apiOrderMasterMapper.selectRentalPictureUrl(rentalVo);
                    if (rentalVos.size() != 0){
                        if (rentalVos.get(0).getShopsName() != null && !"".equals(rentalVos.get(0).getShopsName())) orderVos.get(i).setShopsName(rentalVos.get(0).getShopsName());
                        if (rentalVos.get(0).getRentalUrl() != null && !"".equals(rentalVos.get(0).getRentalUrl())) orderVos.get(i).setPicUrl(rentalVos.get(0).getRentalUrl());
                    }
                }
            }
        }
        return orderVos;
    }

    /**
     * 修改订单状态操作
     * @param orderVo
     * @return
     */
    @Override
    public int updateOrderVo(OrderVo orderVo) {
        System.out.println(orderVo);
        int row = 0;
        row = apiOrderMasterMapper.updateOrderVo(orderVo);
        return row;
    }

    /**
     * 添加订单信息
     * @param orderMaster
     * @return
     */
    public int insertOrderMaster(OrderMaster orderMaster){
        return apiOrderMasterMapper.insertOrderMaster(orderMaster);
    }

    @Autowired
    private CommissionMapper commissionMapper;
    @Autowired
    private CustomerLoginMapper customerLoginMapper;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private CashManagementMapper cashManagementMapper;
    @Autowired
    private PlatformTerraceMapper platformTerraceMapper;
    @Autowired
    private SupplierInfoMapper supplierInfoMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private DistributionSubstationsMapper distributionSubstationsMapper;
    @Autowired
    private DistributionSubMapper distributionSubMapper;
    @Autowired
    private MoneyPercentageMapper moneyPercentageMapper;

    /**
     * 修改订单支付方式
     * @param orderMaster
     * @return
     */
    public int updateOrderMethod(OrderMaster orderMaster){
        orderMaster.setOrderMoney(orderMaster.getPaymentMoney());
        System.err.println("00000000*****************"+orderMaster.getSupplierId());
        //通过 customer_login表中邀请人ID,判断是否是 普通用户 默认是0 还是分销用户
        CustomerLogin customerLogin = tokenUtils.getLoginCustomer(request);
        Long customerId = customerLogin.getCustomerId();//用户人ID
        CustomerLogin custListById = customerLoginMapper.findCustListById(customerId); // 根据用户ID获取到 邀请人ID
        System.err.println("************根据用户ID获取到 邀请人ID*******"+custListById.getInviterId());

        if (custListById.getInviterId() != 0){
            System.err.println("*******************此用户是分销人************************");
            Double totalRevenue=0.00;  //总收益数
            Double clientMoney =0.00;  //客户佣金金额
            Double substationMoney=0.00; //分站佣金金额
            Double commissionMoney=0.00; // 超管佣金金额

            //获取到超管设置的 抽取收益百分比
            Commission commission = new Commission();
            List<Commission> commissions = commissionMapper.selectCommissionList(commission);
            for (Commission listInfo : commissions) {
                Double totalrevenue = listInfo.getTotalRevenue();
                Double clientmoney = listInfo.getClientMoney();
                Double substationmoney = listInfo.getSubstationMoney();
                Double commissionmoney = listInfo.getCommissionMoney();
                totalRevenue = totalrevenue;
                clientMoney =clientmoney;
                substationMoney=substationmoney;
                commissionMoney=commissionmoney;
            }

            // Double 类型转成 BigDecimal
            BigDecimal totalRevenue1 = new BigDecimal(totalRevenue*0.01);
            double paymentMoneyaa = orderMaster.getPaymentMoney();// 获取前端传过来得 金额值
            BigDecimal paymentMoney = new BigDecimal(paymentMoneyaa);

            double zongshouyi = paymentMoney.multiply(totalRevenue1).doubleValue(); //将传过来的金额 乘 超过设置的百分比
            System.err.println("********将传过来的金额 乘 超过设置的百分比********"+zongshouyi);

            BigDecimal kehujine = new BigDecimal(zongshouyi); //获取到 分销出去的钱 转成BigDecimal类型  总分销金额
            System.err.println("*******获取到 分销出去的钱 转成BigDecimal类型********"+kehujine);

            double subtract = paymentMoney.subtract(kehujine).doubleValue();
            System.err.println("*********把 总金额 减去 分销出去的钱 = 订单的金额*************"+ subtract);
            orderMaster.setPaymentMoney(subtract);

//***************用户收益**************
            BigDecimal xiaoshu = new BigDecimal(clientMoney*0.1); //获取到 超管设置的 客户用金比例
            BigDecimal clientMoney1 =xiaoshu.setScale(2, RoundingMode.HALF_UP);//保留两位小数
            System.err.println("********clientMoney1******clientMoney1*********clientMoney1**********"+clientMoney1);
            BigDecimal multiplyxiaoshu = kehujine.multiply(clientMoney1); //将超管设置的总比例 乘与 客户比例 = 客户收益
            double multiply =multiplyxiaoshu.setScale(2, RoundingMode.HALF_UP).doubleValue();//将可客户收益保留两位小数,同时转成doble类型
            System.err.println("***********将可客户收益保留两位小数,同时转成doble类型************"+multiply);
            CashManagement cashManagement = new CashManagement();  //用户佣金收益实体类
            cashManagement.setDepositMoney(multiply);
            cashManagement.setTimedate(new Date());
            cashManagement.setCustomerId(customerId);
            cashManagement.setInviterId(custListById.getInviterId().longValue());
            cashManagementMapper.insertCashManagement(cashManagement);

//***************平台收益**************

            BigDecimal commission1 = new BigDecimal(commissionMoney*0.1);
            BigDecimal bigDecimal = commission1.setScale(2, RoundingMode.HALF_UP);//保留两位小数
            BigDecimal multiply1 = kehujine.multiply(bigDecimal);
            double terraceMoney = multiply1.setScale(2, RoundingMode.HALF_UP).doubleValue();
            PlatformTerrace platformTerrace = new PlatformTerrace(); //平台用金收益实体类
            platformTerrace.setTerraceMoney(terraceMoney);
            platformTerrace.setCustomerId(customerId);
            platformTerrace.setInviterId(custListById.getInviterId().longValue());
            platformTerrace.setModifiedTime(new Date());
            platformTerraceMapper.insertPlatformTerrace(platformTerrace);

//****************分站收益****************

            Integer supplierId = orderMaster.getSupplierId();
            SupplierInfo supplierInfo = supplierInfoMapper.selectSupplierInfoById(supplierId);
            HashMap<String, String> objectObjectHashMap1 = new HashMap<String, String>();
            objectObjectHashMap1.put("address",supplierInfo.getAddress());
            String address = objectObjectHashMap1.get("address");// 获取到店铺的地区
            System.err.println("**********获取到店铺的地区***********"+address);
            SysDept sysDept = new SysDept(); //分站部门实体类
            List<SysDept> sysDepts = sysDeptMapper.selectDeptName(sysDept);//查询出有哪些部门
            int fal =0;
            int tru =0;
            String depName ="";
            for (int i=0;i<sysDepts.size();i++){
                SysDept sysDept1 = sysDepts.get(i);
                System.err.println("************获取到全部分站的部门*************"+sysDept1.getDeptName());
                // 判断 address.contains(sysDept1.getDeptName()) 如果是true的话 说明有分站 给分站分佣金,如果false 则没有这个地区的分站 给超管分佣金
                if(address.contains(sysDept1.getDeptName()) == false){
                    System.err.println("******************此地区没有分站部门**************");
                      fal = fal+1;
                      System.err.println("*********fal********"+fal);

                }else if(address.contains(sysDept1.getDeptName()) == true){
                    System.err.println("******************此地区有分站部门**************");
                    System.err.println("************获取到分站的名称 sysDept1.getDeptName()*******"+sysDept1.getDeptName());
                    depName = sysDept1.getDeptName();
                    tru +=1;
                    System.err.println("*********tru********"+tru);
                }
            }

            System.err.println("********得出的结论fal***********"+fal);
            System.err.println("********得出的结论tru***********"+tru);

            if (tru == 0 && fal>0){
                System.err.println("********tru等于0 和fal大于0说明 没有分站");
                BigDecimal bigDecimal1 = new BigDecimal(substationMoney*0.1); // 获取到超管设置的分站收益比例
                BigDecimal bigDecimal2 = bigDecimal1.setScale(2, RoundingMode.HALF_UP);
                BigDecimal multiply2 = kehujine.multiply(bigDecimal2);
                double substation = multiply2.setScale(2, RoundingMode.HALF_UP).doubleValue();

                PlatformTerrace platformTerrace1 = new PlatformTerrace();
                platformTerrace1.setTerraceMoney(substation);
                platformTerrace1.setCustomerId(customerId);
                platformTerrace1.setInviterId(custListById.getInviterId().longValue());
                platformTerrace1.setModifiedTime(new Date());
                platformTerraceMapper.insertPlatformTerraceOne(platformTerrace1);
            }else if(tru >0){
                System.err.println("********tru大于0 说明 有分站");
                System.err.println("**********depName*****分站地址********"+depName);
                SysDept sysDepts1 = sysDeptMapper.selectFindAll(depName);
                System.err.println("********sysDepts1********"+sysDepts1);

                BigDecimal bigDecimal11 = new BigDecimal(substationMoney*0.1); // 获取到超管设置的分站收益比例
                BigDecimal bigDecimal22 = bigDecimal11.setScale(2, RoundingMode.HALF_UP);
                BigDecimal multiply22 = kehujine.multiply(bigDecimal22);
                double substation = multiply22.setScale(2, RoundingMode.HALF_UP).doubleValue();
                System.out.println("mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm"+substation);
                DistributionSubstations distributionSubstations = new DistributionSubstations();
                distributionSubstations.setDistriSubShouyi(substation);   //金额
                distributionSubstations.setCustomerId(customerId);    //用户id
                distributionSubstations.setDeptId(sysDepts1.getDeptId());
                distributionSubstations.setUserId(sysDepts1.getUserId());
                distributionSubstations.setSupplierId(supplierId.longValue()); //店铺ID
                distributionSubstations.setProductId(orderMaster.getProductId());
                distributionSubstations.setOrderId(orderMaster.getOrderId());
                distributionSubstationsMapper.insertDistributionSubstations(distributionSubstations);

                //查询是否有表
                DistributionSub distributionSubs = distributionSubMapper.selectDistributionSubById(Integer.parseInt(sysDepts1.getDeptId().toString()));//查询当前的金额
                System.out.println("我是存在表数据我是否存在"+distributionSubs);
                if(distributionSubs != null){
                    DistributionSub dsb = new DistributionSub();
                    System.out.println("11111111111111111111111111111111111111111111111111111111111111111111"+distributionSubs.getSumMoney()+substation);
                    dsb.setUser_id(Integer.parseInt(sysDepts1.getUserId().toString()));
                    dsb.setDept_id(Integer.parseInt(sysDepts1.getDeptId().toString()));
                    dsb.setSumMoney(distributionSubs.getSumMoney()+substation);   //存储金额
                    dsb.setSumMoneycopy(distributionSubs.getSumMoney()+substation);
                    MoneyPercentage moneyPercentage = moneyPercentageMapper.selectMoneyPercentageById(1);
                    dsb.setKeMoney(distributionSubs.getSumMoney()+substation-(distributionSubs.getSumMoney()+substation)*moneyPercentage.getPercent()); //可提现金额
                    distributionSubMapper.updateDistributionSub(dsb);
                }else{
                    DistributionSub ds = new DistributionSub();     //创建提现表对象
                    ds.setMoneyStrart("0");
                    ds.setUser_id(Integer.parseInt(sysDepts1.getUserId().toString()));
                    SysDept sysDept1 = sysDeptMapper.selectDeptById(sysDepts1.getDeptId());
                    ds.setDept_name(sysDept1.getDeptName());   //添加部门
                    ds.setDept_id(Integer.parseInt(sysDepts1.getDeptId().toString()));
                    distributionSubMapper.insertDistributionSub(ds);
                    DistributionSub distributionSub = distributionSubMapper.selectDistributionSubById(Integer.parseInt(sysDepts1.getDeptId().toString()));//查询当前的金额
                    System.out.println("*******************************************************"+distributionSub);
                    DistributionSub dsb = new DistributionSub();
                    System.out.println("11111111111111111111111111111111111111111111111111111111111111111111"+distributionSub.getSumMoney()+substation);
                    dsb.setUser_id(Integer.parseInt(sysDepts1.getUserId().toString()));
                    dsb.setDept_id(Integer.parseInt(sysDepts1.getDeptId().toString()));
                    dsb.setSumMoney(distributionSub.getSumMoney()+substation);   //存储金额
                    dsb.setSumMoneycopy(distributionSub.getSumMoney()+substation);
                    MoneyPercentage moneyPercentage = moneyPercentageMapper.selectMoneyPercentageById(1);
                    dsb.setKeMoney(distributionSub.getSumMoney()+substation-(distributionSub.getSumMoney()+substation)*moneyPercentage.getPercent()); //可提现金额
                    distributionSubMapper.updateDistributionSub(dsb);

                }




            }
            return apiOrderMasterMapper.updateOrderMethod(orderMaster);
        }else if (custListById.getInviterId() == 0){
            System.err.println("****************此用户是普通用户*******************");
        }
        return apiOrderMasterMapper.updateOrderMethod(orderMaster);
    }

    /**
     * 微信支付
     * @param zhiFuVo
     * @return
     */
    @Override
    public ZhiFuVo weiXinZhiFu(ZhiFuVo zhiFuVo) {
        return apiOrderMasterMapper.selectZhiFuVo(zhiFuVo);
    }

    /**
     * 全部订单中的去付款中的线下支付方法
     * @param orderVo
     * @return
     */
    @Override
    public int updateOrderVoThree(OrderVo orderVo) {
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setOrderId((int) orderVo.getOrderId());
        orderMaster.setPaymentMethod(5);
        orderMaster.setPayTime(new Date());
        orderMaster.setOrderStatus(2);
        return apiOrderMasterMapper.updateOrderMethod(orderMaster);
    }

    @Override
    public OrderMaster getOrderShoppingCode(OrderMaster orderMaster) {
        return apiOrderMasterMapper.getOrderShoppingCode(orderMaster);
    }

}
